/**
 * description:axios
 * */
import axios from 'axios';
import {Toast} from 'vant'
import store from '../store';
import router from '../router';
axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? '/api' : '/api';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.interceptors.request.use((config) => {
    let adminToken = store.state.adminToken || '';
    if (adminToken) {
        config.headers['Authorization'] = 'Bearer ' + adminToken;
    }
    return config;
}, error => {
    return Promise.reject(error);
});
axios.interceptors.response.use((response) => {
    if (response.status === 200) {
        // 过期
        if (response.data.code && response.data.code === 401) {
            store.commit('setToken', '');
            router.push({
                path: '/login'
            })
        } else if (response.data) {
            return response.data;
        } else {
            let error = new Error();
            error.msg = response.data.msg || '系统出错，请联系管理员';
            return Promise.reject(error);
        }
    } else {
        let error = new Error();
        error.msg = response.msg || '请求失败';
        error.code = response.code;
        error.data = response.data;
        Toast.fail(error.msg);
        return Promise.reject(error);
    }
}, error => {
    // 请求错误
    if (error && error.response) {
        let err = new Error();
        err.message = '系统出错，请联系管理员';
        err.code = error.response.status;
        err.data = error.response.data;
        Toast.fail(err.message);
        return Promise.reject(err);
    } else {
        let err = new Error();
        err.message = '网络问题，请检查网络设置或稍后重试';
        err.code = 0;
        err.data = 'null';
        // Toast.fail(err.message);
        return Promise.reject(err);
    }
});

export default axios;
